package cn.shyouchi.wuguanjia.android.api.patrol;

import android.content.Context;
import android.text.TextUtils;

import com.alibaba.fastjson.JSON;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.shyouchi.wuguanjia.android.api.ClientProvider;
import cn.shyouchi.wuguanjia.android.api.UserStorageProvider;
import cn.shyouchi.wuguanjia.android.components.storage.UserStorage;
import cn.shyouchi.wuguanjia.android.model.BaseRequestResult;
import cn.shyouchi.wuguanjia.android.ui.event.checknum.CheckNumLineEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.PatrolRateEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.begin.PatrolManagerEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.begin.PatrolRingDesEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.report.PatrolErrorEntity;
import cn.shyouchi.wuguanjia.android.ui.patrol.statistic.PatrolStatisticEntity;
import cn.shyouchi.wuguanjia.android.ui.statistic.SignStatisticManagerEntity;
import cn.shyouchi.wuguanjia.android.utils.LogUtil;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import retrofit2.Retrofit;
import rx.Observable;
import rx.functions.Func1;
import rx.schedulers.Schedulers;
import top.zibin.luban.Luban;

/**
 * Created by Eenie on 2017/1/3 at 9:40
 * Email: 472279981@qq.com
 * Des:
 */

public class PatrolApi {


    public static final String BASE_URL = "http://118.178.88.132:8000/api/";
    private PatrolService mService;
    private static final int DEFAULT_TIMEOUT = 100; //超时时间100秒
    private final long DEFAULT_IMG_SIZE = 1024 * 1024;//上传图片不能大于1M
    private UserStorage mUserStorage;
    private Context mContext;

    public PatrolApi(Context context) {
        mUserStorage =  UserStorageProvider.Default();

        mContext = context;
        Retrofit retrofit =  ClientProvider.getDefaultClient().getRetrofit();
        mService = retrofit.create(PatrolService.class);
    }


    public Observable<CheckNumLineEntity> getPatrolLines() {
        return mService.getPatrolLines(mUserStorage.getToken());
    }

    public Observable<PatrolRingDesEntity> getPatrolLineRings(String lineid) {
        return mService.getPatrolLinePoints(mUserStorage.getToken(), lineid);
    }

    public Observable<PatrolRateEntity> getPatrolRate(String lineid) {
        return mService.getPatrolRate(mUserStorage.getToken(), lineid);
    }

    public Observable<PatrolManagerEntity> getManagers() {
        return mService.getManagers(mUserStorage.getToken());
    }

    public Observable<PatrolErrorEntity> getWarrantyList(String type) {
        return mService.getWarrantyList(mUserStorage.getToken(), type);
    }

    public Observable<PatrolStatisticEntity> getStatisticsList(String userid, String startTime, String endTime) {


        Map<String, Object> params = new HashMap<>();
        if (!TextUtils.isEmpty(userid)) {
            params.put("userid", userid);
        }
//        @Query("starttime")String startTime, @Query("endtime")String endTime
        params.put("starttime", startTime);
        params.put("endtime", endTime);

        return mService.getStatisticsList(mUserStorage.getToken(), params);
    }

    public Observable<PatrolStatisticEntity> getMonthStatistic(String projectid, String date) {
        return mService.getMonthStatistic(mUserStorage.getToken(), projectid, date);
    }

//
//    public Observable<BaseRequestResult> submitPatrol(String inspectionpointid,
//                                                      String situation,
//                                                      String completed,
//                                                      String path) {
//
//        final Map<String, RequestBody> paramsMap = new HashMap<>();
//        final RequestBody projectsIdBody = RequestBody.create(MediaType.parse("multipart/form-data"), inspectionpointid);
//        paramsMap.put("inspectionpointid", projectsIdBody);
//        final RequestBody IdBody = RequestBody.create(MediaType.parse("multipart/form-data"), situation);
//        paramsMap.put("situation", IdBody);
//        final RequestBody nameBody = RequestBody.create(MediaType.parse("multipart/form-data"), completed);
//        paramsMap.put("completed", nameBody);
//
//        File file = new File(path);
//
//
//        return Luban.get(mContext)
//                .load(file)
//                .putGear(Luban.THIRD_GEAR)
//                .asObservable()
//                .flatMap(new Func1<File, Observable<BaseRequestResult>>() {
//                    @Override
//                    public Observable<BaseRequestResult> call(File file) {
//                        MultipartBody.Part body = null;
//                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//                        body = MultipartBody.Part.createFormData("image[]", file.getName(), requestFile);
//                        return mService.submitPatrol(mUserStorage.getToken(), paramsMap, body);
//                    }
//                });
//    }

    public Observable<BaseRequestResult> submitPatrols(final Map Object,
                                                       String path,
                                                       ArrayList<String> imgs) {


        final List<MultipartBody.Part> partHashMap = new ArrayList<>();

        final Map<String, RequestBody> paramsMap = new HashMap<>();


        final RequestBody data = RequestBody.create(MediaType.parse("multipart/form-data"), JSON.toJSONString(Object));
        paramsMap.put("data", data);
//        final RequestBody IdBody = RequestBody.create(MediaType.parse("multipart/form-data"), situation);
//        paramsMap.put("situation", IdBody);
//        final RequestBody nameBody = RequestBody.create(MediaType.parse("multipart/form-data"), completed);
//        paramsMap.put("completed", nameBody);

//        File file = new File(path);
//        return Luban.get(mContext)
//                .load(file)
//                .putGear(Luban.THIRD_GEAR)
//                .asObservable()
//                .flatMap(new Func1<File, Observable<BaseRequestResult>>() {
//                    @Override
//                    public Observable<BaseRequestResult> call(File file) {
//                        MultipartBody.Part body = null;
//                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
//                        body = MultipartBody.Part.createFormData("image[]", file.getName(), requestFile);
//                        return mService.submitPatrol(mUserStorage.getToken(), paramsMap, body);
//                    }
//                });


        Observable<MultipartBody.Part> partObservable = Observable.just(path)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<String, Observable<File>>() {
                    @Override
                    public Observable<File> call(String s) {
                        return Observable.just(new File(s));
                    }
                }).flatMap(new Func1<File, Observable<File>>() {
                    @Override
                    public Observable<File> call(File file) {
                        return Luban.get(mContext)
                                .load(file)
                                .putGear(Luban.THIRD_GEAR)
                                .asObservable();
                    }
                }).map(new Func1<File, MultipartBody.Part>() {
                    @Override
                    public MultipartBody.Part call(File file) {
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part body = MultipartBody.Part.createFormData("image[]", file.getName(), requestFile);
                        return body;
                    }
                });


        return Observable.from(imgs)
                .subscribeOn(Schedulers.io())
                .flatMap(new Func1<String, Observable<File>>() {
                    @Override
                    public Observable<File> call(String path) {
                        File file = new File(path);
                        LogUtil.e("file size is " + file.length());
                        if (file.length() > DEFAULT_IMG_SIZE) {
                            LogUtil.e("file start compress , it is too big!");
                            return Luban.get(mContext)
                                    .load(file)
                                    .putGear(Luban.THIRD_GEAR)
                                    .asObservable();
                        } else {
                            LogUtil.e("file not need compress!");
                            return Observable.just(file);
                        }
                    }
                })
                .map(new Func1<File, MultipartBody.Part>() {
                    @Override
                    public MultipartBody.Part call(File file) {
                        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);
                        MultipartBody.Part body = MultipartBody.Part.createFormData("warranty_image[]", file.getName(), requestFile);
                        return body;
                    }
                })
                .concatWith(partObservable)
                .toList()
                .flatMap(new Func1<List<MultipartBody.Part>, Observable<BaseRequestResult>>() {
                    @Override
                    public Observable<BaseRequestResult> call(List<MultipartBody.Part> parts) {
                        partHashMap.addAll(parts);
                        return mService.submitPatrol(mUserStorage.getToken(), paramsMap, partHashMap);
                    }
                });


    }


    public Observable<SignStatisticManagerEntity> getEvents() {
        return mService.getEvents(mUserStorage.getToken());
    }


//    public Observable<BaseRequestResult> submitPatrol(Object params) {
//        return mService.submitPatrol(mUserStorage.getToken(), JSON.toJSONString(params));
//
//    }


}
